package com.sansecy.customview.roundview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Outline;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.util.AttributeSet;
import android.view.View;
import android.view.ViewOutlineProvider;

import com.sansecy.customview.R;


public class CornerConstraintLayout extends ConstraintLayout {
    private static final float DEFAULT_CORNER_SIZE = 15;
    private Path roundPath;
    private float cornerSize = DEFAULT_CORNER_SIZE;
    private int canvasWidth;
    private int canvasHeight;
    private boolean enableClipPath;

    public CornerConstraintLayout(@NonNull Context context) {
        super(context);
    }

    public CornerConstraintLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initFromAttributes(context, attrs);
    }

    public CornerConstraintLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initFromAttributes(context, attrs);
    }

    @Override
    public void dispatchDraw(Canvas canvas) {
        if (enableClipPath) {
            if (roundPath == null || canvasWidth != canvas.getWidth() || canvasHeight != canvas.getHeight()) {
                roundPath = new Path();
                canvasWidth = canvas.getWidth();
                canvasHeight = canvas.getHeight();
                roundPath.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), cornerSize, cornerSize, Path.Direction.CW);
            }
            canvas.clipPath(roundPath);
        }
        super.dispatchDraw(canvas);
    }

    private void initFromAttributes(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CornerConstraintLayout);
        cornerSize = a.getDimension(R.styleable.CornerFrameLayout_spCornerSize, DEFAULT_CORNER_SIZE);
        a.recycle();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setOutlineProvider(new ViewOutlineProvider() {
                @Override
                public void getOutline(View view, Outline outline) {
                    outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), cornerSize);
                }
            });
            setClipToOutline(true);
            enableClipPath = false;
        } else {
            enableClipPath = true;
        }
    }

}
